package com.it.config;

import com.it.interceptor.JwtTokenInterceptor;
import com.it.json.JacksonObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;
import java.util.concurrent.Executor;

@Configuration
@Slf4j
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    @Autowired
    private JwtTokenInterceptor jwtTokenInterceptor;

    @Autowired
    @Qualifier("taskExecutor")
    private Executor taskExecutor;

    /**
     * 添加拦截器
     * @param registry
     */
    protected void addInterceptors(InterceptorRegistry registry) {
        log.info("添加拦截器配置");
        registry.addInterceptor(jwtTokenInterceptor) // 添加拦截器
                .addPathPatterns("/user/**", "/api/user/**")
                .excludePathPatterns("/user/user/login", "/user/user/register");
    }

    /**
     * 添加跨域映射
     * @param registry
     */
    protected void addCorsMappings(CorsRegistry registry) {
        log.info("添加跨域映射");
        registry.addMapping("/**") // 允许所有路径
                .allowedOriginPatterns("*") // 允许所有来源
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的HTTP方法
                .allowCredentials(true) // 允许携带凭证
                .maxAge(3600); // 预检请求的缓存时间（秒）
    }

    /**
     * 配置异步支持
     * 设置自定义的异步任务执行器，替代默认的SimpleAsyncTaskExecutor
     * 
     * @param configurer 异步支持配置器
     */
    @Override
    protected void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        log.info("配置异步支持，使用自定义线程池执行器");
        // 设置异步任务执行器
        configurer.setTaskExecutor((AsyncTaskExecutor) taskExecutor);
        // 设置异步请求超时时间：30秒
        configurer.setDefaultTimeout(30000);
        log.info("异步支持配置完成，超时时间: 30秒");
    }

    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        log.info("添加消息转换器");
        // 创建消息转换器对象
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        // 设置对象转换器，底层使用Jackson将Java对象转为json
        converter.setObjectMapper(new JacksonObjectMapper());
        // 将消息转换器对象追加到converters中
        converters.add(0, converter);
    }
}
